<template>
  <div>
    <!-- 优惠券单元格 -->
    <van-coupon-cell :coupons="isCoupons" :chosen-coupon="chosenCoupon" @click="showList = true" />
    <!-- 优惠券列表 -->
    <van-popup v-model="showList" round position="bottom" style="height: 90%; padding-top: 4px;">
      <van-coupon-list
        :coupons="isCoupons"
        :chosen-coupon="chosenCoupon"
        :disabled-coupons="disabledCoupons"
        @change="onChange"
        @exchange="onExchange"
      />
    </van-popup>
  </div>
</template>

<script>
import { mapMutations, mapActions, mapState } from "vuex";
import { post } from '@/utils/axios'

import Vue from 'vue';
import { CouponCell, CouponList, Popup, Toast } from 'vant';

Vue.use(CouponCell).use(CouponList).use(Popup).use(Toast);
const coupon = {
  // available: 1,
  id: "优惠券 id	string",
  // 左
  condition: "满减条件 无使用门槛\n最多优惠12元",
  value: 150,
  valueDesc: "1.5",
  unitDesc: "元",
  // 右
  name: "优惠券名称",
  startAt: 1590165539.177,
  endAt: 1514592000,
  // 下方
  description: "描述信息，优惠券可用时展示	string",
  reason: "不可用原因，优惠券不可用时展示	string",
};
export default {
  data() {
    return {
      chosenCoupon: -1, // 当前选中优惠券的索引(-1上来是没选中的)
      disabledCoupons: [coupon],
      showList: false
    };
  },
  props: {
    // changeCouponProps
  },
  computed: {
    ...mapState("goodsModule", ["coupons"]),
    ...mapState("userModule", ["userinfo"]),
    isCoupons() {
      if (Array.isArray(this.userinfo.coupons) && this.userinfo.coupons.length > 0) {
        let arr = []
        this.userinfo.coupons.forEach(item => {
          let obj = this.coupons.filter(one => one.id === item.split('#')[0])[0];
          arr.push({
            ...obj,
            id: item
          })
        })
        return arr
      } else {
        return []
      }
    }
  },
  methods: {
    ...mapActions("goodsModule", ["getCouponsAction"]),
    ...mapActions("userModule", ["GETUSERINFO"]),
    onChange(index) {
      this.chosenCoupon = index;
      this.$emit('change-coupon-props', this.isCoupons[index])
      // this.props.changeCouponProps(this.isCoupons[index])
      this.showList = false;
    },
    onExchange(code) {
      post({
        url: "/hybrid/uni/add-couponse-code",
        data: {
          code
        }
      }).then(res => {
        this.GETUSERINFO()
        Toast({
        message: res.msg,
        closeOnClick: true,
        forbidClick: true,
        duration: 500
      });
      })
      // this.coupons.push(coupon);
    }
  },
  mounted() {
    if (!this.coupons) {
      this.getCouponsAction()
    }
    // console.log(this.userinfo, this.coupons)
  }
}
</script>

<style>
</style>